package com.soriya.nestlive

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.BrokenImage
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.soriya.nestlive.application.MyApplication
import com.soriya.nestlive.router.ScreenPath
import com.soriya.nestlive.router.routingTable
import com.soriya.nestlive.ui.theme.NestLiveTheme
import com.soriya.nestlive.util.ToastUtil
import com.yalantis.ucrop.UCrop
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    @RequiresApi(Build.VERSION_CODES.Q)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NestLiveTheme {
                InitPermission()

                val initScreen: ScreenPath = ScreenPath.Home

                var currentRoute: ScreenPath? by remember {
                    mutableStateOf(null)
                }

                var hasBack by remember {
                    mutableStateOf(false)
                }

                val navController = rememberNavController()

                navController.addOnDestinationChangedListener { controller, destination, _ ->
                    hasBack = controller.previousBackStackEntry != null
                    var route = destination.route ?: initScreen.route
                    route = route.run {
                        indexOf("/").takeIf {
                            it != -1
                        }?.let {
                            substring(0, it)
                        } ?: this
                    }
                    currentRoute = ScreenPath.valueOf(route)
                }

                val navGraph = remember(navController) {
                    routingTable(navController = navController, startDestination = initScreen.route)
                }

                Scaffold(
                    bottomBar = {
                        takeIf {
                            currentRoute?.isBottomNav ?: false
                        }?.let {
                            val backStackEntry by navController.currentBackStackEntryAsState()
                            val destination = backStackEntry?.destination
                            BottomNavigation(
                                backgroundColor = MaterialTheme.colors.background,
                                contentColor = MaterialTheme.colors.primary
                            ) {
                                ScreenPath.values()
                                    .filter { it.isBottomNav }
                                    .forEach { screen ->
                                        BottomNavigationItem(
                                            selected = destination?.hierarchy?.any { it.route == screen.route } == true,
                                            onClick = {
                                                navController.popBackStack()
                                                navController.navigate(screen.route) {
                                                    popUpTo(navController.graph.findStartDestination().id) {
                                                        inclusive = true
                                                    }
                                                    launchSingleTop = true
                                                }
                                            },
                                            icon = {
                                                Icon(
                                                    imageVector = screen.icon ?: Icons.Default.BrokenImage,
                                                    contentDescription = screen.route,
                                                    modifier = Modifier.size(32.dp)
                                                )
                                            }
                                        )
                                }
                            }
                        }
                    },
                    topBar = {
                        takeIf {
                            currentRoute?.isTopBar ?: true
                        }?.let {
                            TopAppBar(
                                title = {
                                    Text(text = currentRoute?.let { resources.getString(it.title) } ?: "")
                                },
                                navigationIcon = takeIf {
                                    hasBack
                                }?.let {
                                    {
                                        IconButton(onClick = {
                                            navController.navigateUp()
                                        }) {
                                            Icon(
                                                imageVector = Icons.Filled.ArrowBack,
                                                contentDescription = "Back"
                                            )
                                        }
                                    }
                                },
                                backgroundColor = MaterialTheme.colors.background,
                                contentColor = MaterialTheme.colors.primary
                            )
                        }
                    }
                ) { paddingValues ->
                    NavHost(
                        navController = navController,
                        graph = navGraph,
                        modifier = Modifier.padding(paddingValues)
                    )
                }
            }
        }
    }

    @Composable
    private fun InitPermission() {
        val PERMISSIONS = arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
        )

        val permissionLauncher = rememberLauncherForActivityResult(
            contract = ActivityResultContracts.RequestMultiplePermissions(),
            onResult = { isGranteds ->
                var allGranted = false
                for ((_, isGranted) in isGranteds) {
                    allGranted = isGranted
                }
                if (allGranted) {
                    ToastUtil.show(this, "授权成功")
                } else {
                    ToastUtil.show(this, "授权失败")
                }
            }
        )

        LaunchedEffect(Unit) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                var check = PackageManager.PERMISSION_GRANTED
                for (permission in PERMISSIONS) {
                    check = ContextCompat.checkSelfPermission(this@MainActivity, permission)
                    if (check != PackageManager.PERMISSION_GRANTED) break
                }
                val hasPermission = check == PackageManager.PERMISSION_GRANTED
                if (!hasPermission) {
                    // 没有全部的权限，申请权限
                    permissionLauncher.launch(PERMISSIONS)
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == -1) {
            if (requestCode == UCrop.REQUEST_CROP && data != null) {
                val uri = UCrop.getOutput(data)
                MyApplication.instance.imageResult.value = uri
            }
        }
//        Log.i("SoRiya", "onActivityResult: $resultCode -- ${requestCode == UCrop.REQUEST_CROP}")
    }
}